dojo.require("dijit.MenuBar");
dojo.require("dijit.MenuBarItem");
dojo.require("dijit.PopupMenuBarItem");
dojo.require("dijit.Menu");
dojo.require("dijit.Tooltip");
dojo.require("dijit.MenuItem");
dojo.require("dijit.PopupMenuItem");
dojo.require("dojox.xml.parser");
dojo.require("dijit.Dialog");
dojo.require("dojo.io.iframe");
dojo.require("dijit.form.Button");
dojo.require("dojox.form.FileInput");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.BorderContainer");

var pMenuBar;
dojo.addOnLoad(function() {
	changeStatus('A_AVAILABLE')
	//setTimerFunctions()
	getOnlineUsersFrmServer()
	receiveMessagesFrmServer()
	document.getElementById("loading").style.display = "none";
	resetSessionTimers()
});
function changeStatus(status) {
	image = getImageName(status)
	document.getElementById("status").innerHTML = "<img src='images/" + image
			+ ".png' />"
	updateStausToServer(status)
	if (status == 'LOGOUT') {
		// window.close();
		window.location = '<%=googleUserService.createLoginURL(((HttpServletRequest) request).getRequestURI())%>'
	}
}

/**
 * Processes the online user list coming in xml format
 * @param xml
		<users>
			<user>
				<loginid>
				</loginid>
				<status>
				</status>
				<displayName>
				</displayName>
				<imagepath>
				</imagepath>
				<frndstatus>
				</frndstatus>
			</user>
		</users>
 * 
 * 
 * @return array of online users 
 * 	0 th element of the row - login id
 *  1 st element of the row - status
 *  2 nd element of the row - display name
 *  3 rd element of the row - image path
 *  4 th element of the row - Status of the friend request
 */
function populateOnlineUsers(xml) {
	// Parse text and generate an XML DOM
	var dom = dojox.xml.parser.parse(xml);
	var docNode = dom.documentElement;

	var users = new Array();
	// Iterate over user
	for ( var i = 0; i < docNode.childNodes.length; i++) {
		// Get Details of the user
		x = dojox.xml.parser.innerXML(docNode.childNodes[i]);
		docNode1 = dojox.xml.parser.parse(x).documentElement;

		users[i] = new Array(5)
		for ( var j = 0; j < docNode1.childNodes.length; j++) {
			users[i][j] = dojox.xml.parser.textContent(docNode1.childNodes[j])
		}
	}
	return users;

}

/**
 * Processes messages for the user coming in xml format
 * 
 * @param xml
	 <messages>
		<message>
			<loginid>
			</loginid>
			<message>
			</message>
			<time>
			</time>
		</message>
	<messages>
	
 * @return array of messages
 * 	0 th element of the row - login id
 *  1 st element of the row - message
 *  2 nd element of the row - time of the message
 * 
 *  */
function populateMessages(xml) {
	var dom = dojox.xml.parser.parse(xml);
	var docNode = dom.documentElement;

	var messages = new Array();
	// Iterate over messages
	for ( var i = 0; i < docNode.childNodes.length; i++) {
		// Get Details of the user
		x = dojox.xml.parser.innerXML(docNode.childNodes[i]);
		docNode1 = dojox.xml.parser.parse(x).documentElement;

		messages[i] = new Array(3)
		for ( var j = 0; j < docNode1.childNodes.length; j++) {
			messages[i][j] = dojox.xml.parser
					.textContent(docNode1.childNodes[j])
		}
	}
	return messages;

}

function getOnlineUsersFrmServer() { //
	dojo.xhrGet( { // 
				// The following URL must match that used to test the server.
				url : "getusers?currentUser=" + localuser + "&rnd="
						+ randomNumber(),
				handleAs : "text",

				timeout : 5000, // Time in milliseconds

				// The LOAD function will be called on a successful response.
				load : function(response, ioArgs) { //
					updateContactList(response); // 
					if (enableAutoRefresh) {
						onlineUserTimeoutId = setTimeout("getOnlineUsersFrmServer()",
								onlineUserTimeout);
					}
					return response; // 
				},

				// The ERROR function will be called in an error case.
				error : function(response, ioArgs) { // 
					console.error("HTTP status code: ", ioArgs.xhr.status); //
					dojo.byId("replace").innerHTML = 'Loading the ressource from the server did not work'; //  
					return response; // 
				}
			});
}

function sendMessageToServer(textMessage, toUser) { // 
	dojo.xhrGet( { // 
				// The following URL must match that used to test the server.
				url : "send?currentUser=" + localuser + "&textMessage="
						+ textMessage + "&toUser=" + toUser + "&rnd="
						+ randomNumber(),
				handleAs : "text",

				timeout : 5000, // Time in milliseconds

				// The LOAD function will be called on a successful response.
				load : function(response, ioArgs) { //
					return response; // 
				},

				// The ERROR function will be called in an error case.
				error : function(response, ioArgs) { // 
					console.error("HTTP status code: ", ioArgs.xhr.status); //
					dojo.byId("replace").innerHTML = 'Loading the ressource from the server did not work'; //  
					return response; // 
				}
			});
}

function updateStausToServer(status) { // 
	dojo.xhrGet( { // 
				// The following URL must match that used to test the server.
				url : "statuschange?currentUser=" + localuser + "&status="
						+ status + "&rnd=" + randomNumber(),
				handleAs : "text",

				timeout : 5000, // Time in milliseconds

				// The LOAD function will be called on a successful response.
				load : function(response, ioArgs) { //
					return response; // 
				},

				// The ERROR function will be called in an error case.
				error : function(response, ioArgs) { // 
					console.error("HTTP status code: ", ioArgs.xhr.status); //
					dojo.byId("replace").innerHTML = 'Loading the ressource from the server did not work'; //  
					return response; // 
				}
			});
}

function receiveMessagesFrmServer() { // 
	dojo.xhrGet( { // 
				// The following URL must match that used to test the server.
				url : "receive?currentUser=" + localuser + "&rnd="
						+ randomNumber(),
				handleAs : "text",

				timeout : 5000, // Time in milliseconds

				// The LOAD function will be called on a successful response.
				load : function(response, ioArgs) { //
					receiveMessage(response); //
					
					return response; // 
				},

				// The ERROR function will be called in an error case.
				error : function(response, ioArgs) { // 
					console.error("HTTP status code: ", ioArgs.xhr.status); //
					dojo.byId("replace").innerHTML = 'Loading the ressource from the server did not work'; //  
					return response; // 
				}
			});
}
function removeMessagesFrmServer() { // 
	dojo.xhrGet( { // 
				// The following URL must match that used to test the server.
				url : "removemessage?currentUser=" + localuser + "&rnd="
						+ randomNumber(),
				handleAs : "text",

				timeout : 5000, // Time in milliseconds

				// The LOAD function will be called on a successful response.
				load : function(response, ioArgs) { //
						if (enableAutoRefresh) {
							messageReceiveTimoutId = setTimeout("receiveMessagesFrmServer()",
									messageRefreshTimeout);
						}	
					return response; // 
				},

				// The ERROR function will be called in an error case.
				error : function(response, ioArgs) { // 
					console.error("HTTP status code: ", ioArgs.xhr.status); //
					dojo.byId("replace").innerHTML = 'Loading the ressource from the server did not work'; //  
					return response; // 
				}
			});
}

function updateUserToServer(reqParams) { //
	dojo.xhrGet( { // 
				// The following URL must match that used to test the server.
				url : "update?currentUser=" + localuser + "&rnd="
						+ randomNumber() + reqParams,
				handleAs : "text",

				timeout : 5000, // Time in milliseconds

				// The LOAD function will be called on a successful response.
				load : function(response, ioArgs) { //
					if (reqParams.indexOf("ADDFRIEND") != -1){
						document.getElementById('newUser').value=""
						alert("Invited friends successfully")
						dijit.byId('inviteFriend').hide()
						
					} else if (reqParams.indexOf("UPDATEDISPNAME") != -1){
						document.getElementById('headerDisplayName').innerHTML = "("+document.getElementById('newDisplayName').value+")"
						document.getElementById('newDisplayName').value=""
							alert("Display Name is changed successfully")
							dijit.byId('updateDisplayName').hide()
							
					} else if (reqParams.indexOf("UPDATEFRNDREQ") != -1){
						alert("Your request has been processed successfully. It will be reflected shortly.")
						getOnlineUsersFrmServer()
					} else if (reqParams.indexOf("ADDIMAGE") != -1){
						alert("Your request has been processed successfully. It will be reflected shortly.")
						localUserImagePath = getValueFrmReqParams(reqParams, "AGE&image")
					}
					
					return response; // 
				},

				// The ERROR function will be called in an error case.
				error : function(response, ioArgs) { // 
					console.error("HTTP status code: ", ioArgs.xhr.status); //
					dojo.byId("replace").innerHTML = 'Loading the ressource from the server did not work'; //  
					return response; // 
				}
			});
}

function uploadImage(){
	actionStr = document.getElementById('uploadAction').value
	var td = dojo.io.iframe.send({
		url: actionStr,
		form: "frmIO",
		method: "post",
		content: {fnx:x},
		timeoutSeconds: 5,
		preventCache: true,
		handleAs: "json",
		handle: function(res, ioArgs){
				document.getElementById('myfile').value = ''
				document.getElementById('uploadFileStatus').innerHTML= "File is uploaded successfully. <br>Please log out for changes to take effect. <br> <a href=# onclick=javascript:dijit.byId('uploadDialog').hide();> Close </a>" 
			},							
		error: function (res,ioArgs) {alert('Error2')}
	});
}
